


let Vue


class VueRouter {
    constructor(options) {
        // 获取路由配置
        // console.log(options)
        this.options = options

        // Vue.util.defineReactive(this,'current',window.location.hash.slice(1) || '/')

        this.current = window.location.hash.slice(1) || '/'

        Vue.util.defineReactive(this, 'matched', [])

        this.match()

        window.addEventListener('hashchange', () => {
            this.current = window.location.hash.slice(1)
            this.matched = []
            this.match()
        })

    }

    match(routes) {
        routes = routes || this.options.routes
        for (let route of routes) {
            if (route.path === '/' && this.current === '/') {
                this.matched.push(route)
                return
            }

            if (route.path !== '/' && this.current.includes(route.path)) {
                this.matched.push(route)
                route.children && this.match(route.children)
                return
            }
        }
    }
}

VueRouter.install = function (_Vue) {
    Vue = _Vue
    Vue.mixin({
        beforeCreate() {
            // console.log(this.$options.router) ??
            if (this.$options.router) {
                Vue.prototype.$router = this.$options.router
            }
        }
    })

    Vue.component('router-view', {
        render(h) {
            this.$vnode.data.routerView = true
            let depth = 0
            let parent = this.$parent
            while (parent) {
                const vnodeData = parent.$vnode && parent.$vnode.data
                if (vnodeData) {
                    vnodeData.routerView && depth++
                }
                parent = parent.$parent
            }
            // console.log(depth,this.$router.matched)
            let component = null
            // const router = this.$router.options.routes.find(val=>val.path === this.$router.current)
            const router = this.$router.matched[depth]
            router && (component = router.component)
            return h(component)
        }
    })

    Vue.component('router-link', {
        props: {
            to: {
                type: String,
                required: true
            }
        },
        render(h) {
            // <a href='#/index'/>
            return h('a', { attrs: { href: '#' + this.to } }, this.$slots.default)
        }
    })
}



export default VueRouter